package com.woniuxy.auth.controller;

import com.woniuxy.auth.service.AuthService;
import com.woniuxy.commons.dto.AuthDto;
import com.woniuxy.commons.entity.User;
import com.woniuxy.commons.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author： 雷鹏
 * Date: 2020/7/21 17:55
 */
@RestController
public class AuthController {


    @Autowired
    private RedisTemplate<String, Object> redisTemlate;

    @Autowired
    private AuthService authService;

    @RequestMapping("/login")
    public AuthDto login(User account) {

        // 从数据库中判断账号
        User user = authService.getUser(account);

        System.out.println(user);
        if (user == null) {
            AuthDto authDto = new AuthDto().setCode(201).setMessage("账号不存在");
            return authDto;
        }

        //密码不正确
        if (!user.getPwd().equals(account.getPwd())) {
            AuthDto authDto = new AuthDto().setCode(202).setMessage("密码不正确");
            return authDto;
        }


        // 生成token，refreshtoken
        String refreshToken = UUID.randomUUID().toString();
        String token = JwtUtil.makeToken(user.getAccount());

        // 将token，refreshtoken存放到redis
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token);
        map.put("account", user.getAccount());
        map.put("role", user.getRole());    //角色
        map.put("rid", user.getRid());    //角色

        // 放入redis、同时设置refreshtoken的过期时间
        redisTemlate.opsForHash().putAll(refreshToken, map);
        redisTemlate.expire(refreshToken, JwtUtil.REFRESH_TOKEN_EXPRE_TIME, TimeUnit.MILLISECONDS);

        // 将token、refreshtoken返回给浏览器
        AuthDto authDto = new AuthDto().setCode(200).setMessage("成功").setRefreshToken(refreshToken).setToken(token).setRole(user.getRole());
        return authDto;

    }

    // 刷新token，生成新的token
    @PostMapping("/refresh/{refreshToken}")
    public AuthDto refresh(@PathVariable("refreshToken") String refreshToken) {

        Map<Object, Object> data = redisTemlate.opsForHash().entries(refreshToken);
        String account = (String) data.get("account");
        String role = (String) data.get("role");
        Integer rid = (Integer) data.get("rid");

        String token = JwtUtil.makeToken(account);

        // 将token，refreshtoken存放到redis
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token);
        map.put("account", account);
        map.put("role", role);    //角色
        map.put("rid", rid);

        redisTemlate.opsForHash().putAll(refreshToken, map);
        AuthDto authDto = new AuthDto().setCode(200).setMessage("成功").setRefreshToken(refreshToken).setToken(token);

        return authDto;
    }

    // 验证角色方法
    @PostMapping("/hasRole/{refreshToken}/{role}")
    public boolean hasRole(@PathVariable("refreshToken") String refreshToken, @PathVariable("role") String role) {

        // 通过refreshToken去redis中查询出当前用户
        Map<Object, Object> data = redisTemlate.opsForHash().entries(refreshToken);
        String account = (String) data.get("account");
        String redisrole = (String) data.get("role");
        int rid = (int) data.get("rid");
        System.out.println(redisrole);
        System.out.println(account);

        List<String> roles = null;
        //如果角色是教师，根据角色和rid去数据库中查询角色信息
        if (redisrole.equals("teacher")) {
            roles = new ArrayList<>();
            roles.add(redisrole);
            if (authService.isMaster(rid)) {
                roles.add("master");
            }
            if (authService.isGrade(rid)) {
                roles.add("grade");
            }

        } else {
            roles = Arrays.asList(redisrole);
        }

        System.out.println(roles);
        if (roles.contains(role)) {
            return true;
        }

        return false;
    }


}
